package demo.mqserver.core;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import demo.common.ConsumerEnv;
import lombok.Data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

//队列
@Data
public class MSGQueue {

    //身份标识
    private String name;

    //持久化
    private boolean durable = false;

    //属性为 true，这个队列只能被一个消费者使用  false 都可以使用（不实现）
     private boolean exclusive = false;

    //自动删除（不实现）
    private boolean autoDelete = false;

    //参数配置（不实现）
    private Map<String, Object> arguments = new HashMap<>();

    //当前队列都有哪些消费者订阅
    private List<ConsumerEnv> consumerEnvList = new ArrayList<>();

    //
    private AtomicInteger consumerSeq = new AtomicInteger(0);


    //添加一个新的订阅者
    public void addConsumerEnv(ConsumerEnv consumerEnv){
        consumerEnvList.add(consumerEnv);
    }

    //订阅者的删除暂时不考虑

    //挑选一个订阅者，用来处理当前的消息（按照轮询的方式）
    public ConsumerEnv chooseConsumer(){
        if(consumerEnvList.size() == 0){
            //该队列没有人订阅
            return null;
        }
        //计算当前要取的元素的下标
        int index = consumerSeq.get() % consumerEnvList.size();
        consumerSeq.getAndIncrement();
        return consumerEnvList.get(index);
    }



    public String getArguments(){
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(arguments);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "{}";
    }

    public void setArguments(String argumentsJson){
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            this.arguments = objectMapper.readValue(argumentsJson, new TypeReference<HashMap<String, Object>>() {});
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }


    public Object getArguments(String key){
        return arguments.get(key);
    }

    public void setArguments(String key, Object val){
        arguments.put(key, val);
    }

    public void setArguments(Map<String, Object> arguments){
        this.arguments = arguments;
    }
}
